/*/{Protheus.doc} SYNCMER
E a User Function de geracao do layout MER (Mercadorias) do Sistema Synchro
@author Elton Teodoro Alves
@since 14/11/2014
@version P11 R5
@Param aParam,Array,Array enviado pelo schudele
@Example
Esta User Function foi desenvolvida para ser utilizada com o Schudele, que passa como parametro para User Function um array com a seguinte configuracao:</br>
</br>
<table>
<tr><th> POSICAO </th><th> TIPO </th><th> DESCRICAO             </th></tr>
<tr><td> [01]    </td><td> C    </td><td> Codigo da Empresa     </td></tr>
<tr><td> [02]    </td><td> C    </td><td> Codigo da Filial      </td></tr>
<tr><td> [03]    </td><td> C    </td><td> Codigo do Agendamento </td></tr>
<tr><td> [04]    </td><td> C    </td><td> Codigo da Tarefa      </td></tr>
</table>
</br>
Para teste fora do schudele, pode-se enviar para o SmartClient com a clausula -a estes dados separadas por virgula ',' Ex.: 99,01,0001,0001
/*/

#Define CRLF Chr(13) + Chr(10)
Static PERIOD := 'D'

#Include 'Protheus.ch'

User Function SYNCMER(xParam)
	
	Local	cLayout		:=	Right(ProcName(),3)
	Local	aParam		:=	If(Valtype(xParam) == 'C',Separa(xParam,',',.T.),xParam)
	Local	aSyncEnv	:=	U_SYNCENV(aParam,cLayout,PERIOD)
	Local	cTrab		:=	GetNextAlias()
	Local	cTempTrab	:=	cLayout + Dtos(Date()) + StrTran(Time(),':','')
	Local	cTempFile	:=	GetSrvProfString("StartPath","") + cTempTrab + GetDbExtension()
	Local	cQuery		:=	''
	Local	cQueryBkp	:=	''
	Local	aStru		:=	{}
	Local	nX			:=	0
	Local	aFiliais	:=	StrTokArr(AllTrim(aSyncEnv[10]),'/',)
	Local	cFiliais	:=	''
	Local	nCount		:=	0
	Local	aLstTpProd	:=	StrTokArr(AllTrim(GetMv('MV_SYNC004')),',',)
	Local	cLstTpProd	:=	If(Len(aLstTpProd)>0,'',Space(GetSx3Cache('B1_TIPO','X3_TAMANHO')))
	
	// Monta a string com a lista de filiais para ser utilizada na query
	
	For nX := 1 To Len(aFiliais)
		
		cFiliais += "'" + aFiliais[nX] + "'"
		
		If nX # Len(aFiliais)
			
			cFiliais += ","
			
		End If
		
	Next nX
	
	// Monta a string com a lista de tipos de produto conforme campo B1_TIPO
	
	For nX := 1 To Len(aLstTpProd)
		
		cLstTpProd += "'" + PadR(aLstTpProd[nX],GetSx3Cache('B1_TIPO','X3_TAMANHO'),' ') + "'"
		
		If nX # Len(aLstTpProd)
			
			cLstTpProd += ","
			
		End If
		
	Next Nx
	
	// --------------------------------------------------------------
	// Monta estrutura do arquivo temporario com dados a serem exportados
	// --------------------------------------------------------------
	aAdd(aStru,{'POS0001','C',0008,0}) // ALTERADO_EM
	aAdd(aStru,{'POS0009','C',0003,0}) // ALTERADO_POR
	aAdd(aStru,{'POS0012','C',0001,0}) // CTRL_INSTRUCAO
	aAdd(aStru,{'POS0013','C',0030,0}) // DESCRICAO
	aAdd(aStru,{'POS0043','C',0005,0}) // DFLT_AM_CODIGO_ENTRADA
	aAdd(aStru,{'POS0048','C',0005,0}) // DFLT_AM_CODIGO_SAIDA
	aAdd(aStru,{'POS0053','C',0010,0}) // DFLT_NBM_CODIGO
	aAdd(aStru,{'POS0063','C',0001,0}) // DFLT_OM_CODIGO
	aAdd(aStru,{'POS0064','C',0003,0}) // DFLT_UNI_CODIGO_ENTRADA
	aAdd(aStru,{'POS0067','C',0003,0}) // DFLT_UNI_CODIGO_ESTOQUE
	aAdd(aStru,{'POS0070','C',0003,0}) // DFLT_UNI_CODIGO_SAIDA
	aAdd(aStru,{'POS0073','C',0020,0}) // MERC_CODIGO
	aAdd(aStru,{'POS0093','C',0008,0}) // DT_INICIO
	aAdd(aStru,{'POS0101','C',0015,0}) // COD_BARRA
	aAdd(aStru,{'POS0116','C',0002,0}) // TIPO_ITEM
	aAdd(aStru,{'POS0118','C',0003,0}) // EX_IPI
	aAdd(aStru,{'POS0121','C',0006,0}) // COD_LST
	aAdd(aStru,{'POS0127','C',0007,0}) // ALIQ_ICMS
	
	// --------------------------------------------------------------
	
	If aSyncEnv[6]
		
		// --------------------------------------------------------------
		// Montagem da query de pesquisa
		// --------------------------------------------------------------
		cQuery	+=	"SELECT " + CRLF
		cQuery	+=	"SB1.B1_XDTINAL POS0001," + CRLF
		cQuery	+=	"SB1.B1_FILIAL POS0009," + CRLF
		cQuery	+=	"'M' POS0012," + CRLF
		cQuery	+=	"SB1.B1_DESC POS0013," + CRLF
		cQuery	+=	"ZB3.ZB3_CDENTR  POS0043," + CRLF
		cQuery	+=	"ZB3.ZB3_CDSAID POS0048," + CRLF
		cQuery	+=	"SB1.B1_POSIPI POS0053," + CRLF
		cQuery	+=	"SB1.B1_ORIGEM POS0063," + CRLF
		cQuery	+=	"SAH.AH_XUMSYNC POS0064," + CRLF
		cQuery	+=	"SAH.AH_XUMSYNC POS0067," + CRLF
		cQuery	+=	"SAH.AH_XUMSYNC POS0070," + CRLF
		cQuery	+=	"SB1.B1_COD POS0073," + CRLF
		cQuery	+=	"SB1.B1_XDTINAL POS0093," + CRLF
		cQuery	+=	"SB1.B1_CODBAR POS0101," + CRLF
		cQuery	+=	"ZB3.ZB3_TPITEM POS0116," + CRLF
		cQuery	+=	"'" + Space(6) + "' POS0118," + CRLF
		cQuery	+=	"'" + Space(3) + "' POS0121," + CRLF
		cQuery	+=	"'+000,00' POS0127" + CRLF
		
		cQuery	+=	"FROM " + RetSqlName("SB1") + " SB1" + CRLF
		
		cQuery	+=	"LEFT JOIN " + RetSqlName("ZB3") + " ZB3" + CRLF
		cQuery	+=	"ON SB1.B1_TIPO = ZB3.ZB3_TIPO AND " + CRLF
		cQuery	+=	"SB1.B1_FILIAL = ZB3.ZB3_FILIAL" + CRLF
		
		cQuery	+=	"LEFT JOIN " + RetSqlName("SAH") + " SAH" + CRLF
		cQuery	+=	"ON SB1.B1_UM = SAH.AH_UNIMED " + CRLF
		
		cQuery	+=	"WHERE SB1.B1_XDTINAL = '" + aSyncEnv[9] + "' AND " + CRLF
		cQuery	+=	"SB1.B1_FILIAL IN(" + cFiliais + ") AND " + CRLF
		cQuery	+=	"SB1.B1_TIPO NOT IN(" + cLstTpProd + ") AND " + CRLF
		cQuery	+=	"SB1.D_E_L_E_T_ <> '*' AND " + CRLF
		cQuery	+=	"SB1.B1_MSBLQL <> 'S' AND " + CRLF
		cQuery	+=	"ISNULL(ZB3.D_E_L_E_T_,' ') <> '*' AND " + CRLF
		cQuery	+=	"ISNULL(SAH.D_E_L_E_T_,' ') <> '*' " + CRLF
		
		// --------------------------------------------------------------
		
		cQueryBkp	:=	cQuery
		
		cQuery := ChangeQuery(cQuery)
		
		If TcSqlExec(cQuery) < 0
			
			U_SYNCMAIL(AllTrim(aSyncEnv[15]),cLayout + ' - ' + AllTrim(aSyncEnv[17]),'Erro na execucao da query no banco de dados: ' + Chr(13) + Chr(10) + AllTrim(TcSqlError()),AllTrim(SubStr(aSyncEnv[4],1,6)),AllTrim(SubStr(aSyncEnv[4],7,6)),1,aSyncEnv[8],aSyncEnv[9])
			
		Else
			
			DbUseArea(.T.,"TOPCONN",TCGenQry(,,cQuery),cTrab,.F.,.T.)
			
			U_SYNCLOG(;
				'Agenda : ' +  SubStr(aSyncEnv[4],1,6) + CRLF +;
				'Tarefa : ' +  SubStr(aSyncEnv[4],7,6) + CRLF +;
				cLayout + ' - ' + AllTrim(aSyncEnv[17]) + CRLF +;
				'Query executada com sucesso: ' + CRLF + cQueryBkp)
			
			// Cria arquivo temporario
			
			fErase(Separa(cTempFile,'\',.T.)[3])
			DbCreate(cTempFile,aStru,__LocalDriver)
			DbUseArea(.T.,__LocalDriver,cTempFile,cTempTrab,.T.,.F.)
			
			U_SYNCLOG(;
				'Agenda : ' +  SubStr(aSyncEnv[4],1,6) + CRLF +;
				'Tarefa : ' +  SubStr(aSyncEnv[4],7,6) + CRLF +;
				'Arquivo Temporario criado com sucesso : ' + cTempFile)
			
			// --------------------------------------------------------------
			// Preenchimento do arquivo temporario
			// --------------------------------------------------------------
			
			(cTrab)->(DbGotop())
			
			Do While .Not. (cTrab)->(EOF())
				
				RecLock(cTempTrab,.T.)
				
				(cTempTrab)->POS0001 := (cTrab)->POS0001
				(cTempTrab)->POS0009 := U_SYNCFIL(aSyncEnv[7],5,(cTrab)->POS0009)
				(cTempTrab)->POS0012 := (cTrab)->POS0012
				(cTempTrab)->POS0013 := (cTrab)->POS0013
				(cTempTrab)->POS0043 := (cTrab)->POS0043
				(cTempTrab)->POS0048 := (cTrab)->POS0048
				(cTempTrab)->POS0053 := If((cTrab)->POS0116 == '09','SERV.IC.O',(cTrab)->POS0053)
				(cTempTrab)->POS0063 := (cTrab)->POS0063
				(cTempTrab)->POS0064 := (cTrab)->POS0064
				(cTempTrab)->POS0067 := (cTrab)->POS0067
				(cTempTrab)->POS0070 := (cTrab)->POS0070
				(cTempTrab)->POS0073 := U_SYNCFIL(aSyncEnv[7],4,(cTrab)->POS0009) + (cTrab)->POS0073
				(cTempTrab)->POS0093 := (cTrab)->POS0093
				(cTempTrab)->POS0101 := (cTrab)->POS0101
				(cTempTrab)->POS0116 := (cTrab)->POS0116
				(cTempTrab)->POS0118 := (cTrab)->POS0118
				(cTempTrab)->POS0121 := (cTrab)->POS0121
				(cTempTrab)->POS0127 := (cTrab)->POS0127
				
				MsUnLock()
				
				(cTrab)->(DbSkip())
				
				nCount++
				
			End Do
			
			// --------------------------------------------------------------
			
			U_SYNCDAT(cTempTrab,aSyncEnv,nCount)
			
			(cTrab)->(DbCloseArea())
			(cTempTrab)->(DbCloseArea())
			fErase(Separa(cTempFile,'\',.T.)[3])
			
		End IF
		
	Else
		
		U_SYNCLOG(;
			'Agenda : ' +  SubStr(aSyncEnv[4],1,6) + CRLF +;
			'Tarefa : ' +  SubStr(aSyncEnv[4],7,6) + CRLF +;
			'Nao foi possivel montar o ambiente de geracao do layout ' + cLayout)
		
	End IF
	
	RpcClearEnv()
	
Return
